import { getZone, updateZone } from '../../../api/user'
import { wxUpload, uploadFileName } from '../../../utils/upload'
import {Event} from '../../../utils/event.js'
const event = new Event()
const app = getApp()

Page({
  data: {
    title: '编辑',
    content: '',
    name: '',
    formats: {},
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    personalInfo: {}
  },
  onLoad: function (options) {
    getZone().then(res => {
      this.setData({
        personalInfo: res
      })
    })
    this.setData({
      title: options.title,
      content: app.globalData[options.name],
      name: options.name
    })
    event.emit('resetEditor', {})
    this.initKeybord()
  },
  initKeybord() {
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({ isIOS})
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      console.log(res.height, 'res.height')
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)
    })
  },
  updatePosition(keyboardHeight) {
    console.log(keyboardHeight, 'keyboardHeight')
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    // let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight - getApp().globalData.navHeight) : windowHeight
    this.setData({ keyboardHeight })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
      // 一进入页面就初始化富文本编辑器，此时还未发送请求获取不到数据，编辑器内容html为空（that.data.articleContent为空）
      // 请求完数据后再调用这个方法，才能取到数据写入编辑器')
      that.editorCtx.setContents({
        html: that.data.content  // 将数据写入编辑器内
      })
    }).exec()
  },
  getEditorValue(e) {
    this.setData({
      content: e.detail.html
    })
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const _this = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        const tempFilePaths = uploadFileName(res.tempFilePaths[0]);
        wxUpload({
          biz: 'OPEN',
          fileName: tempFilePaths,
          size: res.tempFiles[0].size,
          filePath: res.tempFiles[0].path
        }).then(uploadRes => {
          _this.editorCtx.insertImage({
            src: uploadRes.uri,
            width: '100%',
            success: function () {
              console.log('insert image success')
            }
          })
        })
      }
    })
  },

  updateConfirm() {
    let personalInfo = this.data.personalInfo
    personalInfo[this.data.name] = this.data.content
    this.setData({
      personalInfo: personalInfo
    })
    const pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    updateZone(this.data.personalInfo).then(res => {
      wx.navigateBack({
        delta: 1,
        success(res) {
          prevPage.init()
        }
      })
    })
  },
})
